<template>
  <div>
    <!-- 添加或修改数据报告对话框 -->
    <jy-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px" :disabled="isDisabled">
            <el-form-item label="所属试验类型" prop="syType">
              <el-cascader v-model="form.syType" :options="syTypeList" :show-all-levels="false" :props="{ expandTrigger: 'hover', value: 'id', emitPath: false }" style="width: 100%"></el-cascader>
            </el-form-item>
            <!-- <el-form-item label="试验名称" prop="reportName">
              <el-input v-model="form.reportName" placeholder="请输入试验名称" />
            </el-form-item>-->
            <!-- <el-form-item label="试验日期类型" prop="reportDateType">
              <el-radio-group v-model="reportDateType">
                <el-radio :label="'1'">单日期</el-radio>
                <el-radio :label="'0'">时间段</el-radio>
              </el-radio-group>
            </el-form-item> -->
            <el-form-item label="试验日期" prop="reportDate">
              <div class="flex">
                <el-date-picker
                  clearable
                  v-model="form.reportDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择试验日期"
                  :picker-options="beginPickerOptions"
                  style="width: 100%"
                ></el-date-picker>
                <span>～</span>
                <el-date-picker
                  clearable
                  v-model="form.reportDateEnd"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择试验日期"
                  :picker-options="endPickerOptions"
                  style="width: 100%"
                ></el-date-picker>
              </div>
            </el-form-item>
            <!-- <el-form-item label="报告编号" prop="bgCode">
              <el-input v-model="form.bgCode" placeholder="请输入报告编号" />
            </el-form-item>
            <el-form-item label="记录编号" prop="jlCode">
              <el-input v-model="form.jlCode" placeholder="请输入记录编号" />
            </el-form-item> -->
            <el-form-item label="样品编号" prop="ypCode">
              <el-input v-model="form.ypCode" placeholder="请输入样品编号" />
            </el-form-item>
            <el-divider class="tips">
              <span class="text-danger text-mini">以下信息会被引入到excel中，请谨慎填写！</span>
            </el-divider>
            <el-form-item label="抽检标段" prop="checkDeptId">
              <!-- <el-cascader v-model="form.checkDeptId" :options="deptList" :show-all-levels="false" placeholder="总监办需要选择抽检标段"
                           :props="{ expandTrigger: 'hover', value: 'id', emitPath: false }" style="width: 100%;"></el-cascader> -->
              <treeselect
                class="tree-select"
                :style="{ width: '255px', height: '32px', lineHeight: '32px' }"
                :append-to-body="false"
                :show-count="true"
                :flat="true"
                :clearable="false"
                v-model="form.checkDeptId"
                :options="treeData"
                :normalizer="normalizer"
                placeholder="总监办请选择抽检试验室"
              ></treeselect>
            </el-form-item>
            <el-form-item label="工程部位" prop="ypVo.gcbw">
              <el-input v-model="form.ypVo.gcbw" placeholder="请输入工程部位" />
            </el-form-item>
            <el-form-item label="样品名称" prop="ypVo.yangpmc">
              <el-input v-model="form.ypVo.yangpmc" placeholder="请输入样品名称" />
            </el-form-item>
            <el-form-item label="样品状态" prop="ypVo.yangpzt">
              <el-input v-model="form.ypVo.yangpzt" placeholder="请输入样品状态" />
            </el-form-item>
            <el-form-item label="来样时间" prop="ypVo.ypDate">
              <el-date-picker clearable style="width: 100%" v-model="form.ypVo.ypDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择来样时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="样品数量" prop="ypVo.yangpsl">
              <el-input v-model="form.ypVo.yangpsl" placeholder="请输入样品数量（需填写单位）" />
            </el-form-item>
            <el-form-item label="代表数量" prop="ypVo.daibsl">
              <el-input v-model="form.ypVo.daibsl" placeholder="请输入代表数量（需填写单位）" />
            </el-form-item>
            <el-form-item label="分部分项名称" prop="ypVo.fbfxmc">
              <el-input v-model="form.ypVo.fbfxmc" placeholder="请输入分部分项名称" />
            </el-form-item>
            <el-form-item label="取样人" prop="ypVo.ypPerson">
              <el-input v-model="form.ypVo.ypPerson" placeholder="请输入取样人" />
            </el-form-item>
            <el-form-item label="样品来源" prop="tzId">
              <el-input v-model="form.tzStr" readonly placeholder="请选择双击样品来源" @dblclick.native="showBsJctzView()" />
            </el-form-item>
            <el-form-item v-if="form.reportResult == 2" label="处理方法" prop="clff">
              <el-input v-model="form.clff" placeholder="请输入处理方法" />
            </el-form-item>
            <el-form-item v-if="form.reportResult == 2" label="处理结果" prop="cljg">
              <el-input v-model="form.cljg" placeholder="请输入处理结果" />
            </el-form-item>
            <el-form-item label="物联引入" prop="dataJsonLabel">
              <el-input v-model="form.dataJsonLabel" placeholder="是否引入物联数据" disabled />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12">
          <el-form :model="reportGroupParams" size="small" :inline="true" label-width="0px" class="top-left">
            <el-form-item label>
              <el-input v-model="reportGroupParams.groupName" placeholder="请输入分组名称" clearable @keyup.enter.native="handleQuery" style="width: 180px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain icon="el-icon-search" size="mini" @click="getBsReportGroup">搜索</el-button>
            </el-form-item>
          </el-form>
          <el-table
            border
            stripe
            ref="groupTable"
            v-loading="typeLoading"
            :data="bsReportGroupList"
            :highlight-current-row="true"
            @current-change="handleCurrentChange"
            row-key="excelTypeId"
            max-height="168px"
            :row-class-name="isCopy ? 'no-select' : ''"
          >
            <el-table-column width="50" label="选择" class-name="radio-border">
              <template slot-scope="scope">
                <el-radio :label="scope.row.id" v-model="currentGroup">{{ "" }}</el-radio>
              </template>
            </el-table-column>
            <el-table-column label="序号" type="index" width="50px" align="center" />
            <el-table-column label="自定义分组名称" prop="groupName" align="center" min-width="180" show-overflow-tooltip />
          </el-table>
          <el-row :gutter="10" class="mb5 mt5 top-right-btn small-line-height">
            <el-col :span="1.5">
              <el-button type="primary" plain size="mini" @click="onAddGroup" :disabled="isDisabled">保存分组</el-button>
            </el-col>
          </el-row>
          <el-table
            border
            stripe
            ref="typeTable"
            v-loading="typeLoading"
            :data="biExcelTypeList"
            @selection-change="selectionChange"
            row-key="excelTypeId"
            max-height="294px"
            :header-row-class-name="isCopy ? 'no-select' : ''"
            :row-class-name="isCopy ? 'no-select' : ''"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" type="index" width="50px" align="center" />
            <el-table-column label="试验名称" prop="excelTypeName" align="center" min-width="180" show-overflow-tooltip />
          </el-table>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="handleWlsj">物联数据引入</el-button>
        <el-button size="small" :loading="buttonLoading" type="primary" @click="submitForm" v-if="!isDisabled">确 定</el-button>
        <el-button size="small" @click="cancel">{{ isDisabled ? "关 闭" : "取 消" }}</el-button>
      </div>
    </jy-dialog>
    <bs-report-group-view ref="bsReportGroupViewRef" :syTypeList="syTypeList" :syType="form.syType" :biExcelTypeList="biExcelTypeList" @callBack="getBsReportGroup" />
    <bs-jctz-view ref="bsJctzViewRef" @callBack="bsJctzCallBack" />
    <introduceIoTdataView ref="introduceIoTdataView" @tableSelection="tableSelection" />
  </div>
</template>
<script>
import { getBsDataReport, addBsDataReport, updateBsDataReport, copyBsDataReport } from "@/api/syrw/bsDataReport";
import { listBsReportGroup } from "@/api/syrw/bsReportGroup";
import { listBiExcelType } from "@/api/syrw/biExcelType";
import { getRuleRes } from "@/api/sycs/bsRule";
import BsReportGroupView from "@/views/syrw/bsReportGroup/BsReportGroupView.vue";
import introduceIoTdataView from "./introduceIoTdataView.vue";
import BsJctzView from "../../ycl/bsJctz/BsJctzView.vue";
import { getDateDiff } from "@/utils";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { BsReportGroupView, BsJctzView, Treeselect, introduceIoTdataView },
  name: "BsDataReportAddOrUpdate",
  computed: {
    treeData: {
      get() {
        return this.$store.state.dept.deptTreeList;
      }
    },
    deptId: {
      get() {
        return this.$store.state.dept.deptId;
      }
    }
  },
  props: {
    syTypeList: {
      type: Array,
      default() {
        return [];
      }
    },
    syType: {
      type: [Number, String],
      default() {
        return "";
      }
    },
    deptList: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      isDisabled: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      groupLoading: false,
      typeLoading: false,
      // 选中数组
      ids: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      reportDateType: "1",
      // reportDateArr: [],
      // 表单参数
      form: {
        excelTypeIdList: [],
        reportDateArr: [],
        ypVo: {
          ypClass: undefined,
          ypDescribe: undefined,
          gcbw: undefined,
          fbfxmc: undefined,
          ypStatus: undefined,
          ypDate: undefined,
          ypPerson: undefined
        }
      },
      // 表单校验
      rules: {
        reportId: [{ required: true, message: "唯一标识一份试验任务不能为空", trigger: "blur" }],
        syType: [{ required: true, message: "所属试验类型不能为空", trigger: "change" }],
        reportDate: [{ required: true, message: "试验日期不能为空", trigger: "blur" }],
        bgCode: [{ required: true, message: "报告编号不能为空", trigger: "blur" }],
        ypCode: [{ required: true, message: "样品编号不能为空", trigger: "blur" }],
        jlCode: [{ required: true, message: "记录编号不能为空", trigger: "blur" }],
        excelTypeId: [{ required: true, message: "Excel类型不能为空", trigger: "blur" }],
        "ypVo.gcbw": [{ required: true, message: "工程部位不能为空", trigger: "blur" }],
        "ypVo.yangpmc": [{ required: true, message: "样品名称不能为空", trigger: "blur" }],
        "ypVo.yangpzt": [{ required: true, message: "样品状态不能为空", trigger: "blur" }],
        "ypVo.ypDate": [{ required: true, message: "来样时间不能为空", trigger: "blur" }],
        "ypVo.yangpsl": [{ required: true, message: "样品数量不能为空", trigger: "blur" }],
        // "ypVo.daibsl": [{ required: true, message: "代表数量不能为空", trigger: "blur" }],
        "ypVo.ypPerson": [{ required: true, message: "取样人不能为空", trigger: "blur" }]
      },
      beginPickerOptions: {
        disabledDate: (time) => {
          let suatus = true;
          if (suatus && this.form.reportDateEnd) {
            suatus = getDateDiff(this.parseTime(time, "{y}-{m}-{d}"), this.form.reportDateEnd, "day") >= 0;
          }
          return !suatus;
        }
      },
      endPickerOptions: {
        disabledDate: (time) => {
          let suatus = true;
          if (suatus && this.form.reportDate) {
            suatus = getDateDiff(this.parseTime(time, "{y}-{m}-{d}"), this.form.reportDate, "day") <= 0;
          }
          return !suatus;
        }
      },
      biExcelTypeList: [], // excel类型 列表
      reportGroupParams: {
        deptId: "",
        syTypeId: "",
        groupName: ""
      },
      bsReportGroupList: [], // 分组列表
      currentGroup: undefined, // 选中的分组
      excelTypeIdList: [],
      tzTypeList: ["clTypeLabel", "guigxh", "supName", "chandcj", "jincsl", "inDate", "cunfwz", "pih"],
      isCopy: false,
      multipleSelection: []
    };
  },
  watch: {
    "form.syType": {
      handler(val) {
        if (!val) {
          return;
        }
        this.getBsReportGroup();
        this.getExcelTypeList();
      }
    }
  },
  created() {},
  methods: {
    async init(id, isView) {
      this.reset();
      this.open = true;
      this.isDisabled = isView;
      if (id) {
        this.title = isView ? "查看数据报告" : "修改数据报告";
        this.form.reportId = id;
        await this.getInfo();
      } else {
        this.title = "添加数据报告";
        await this.getRuleResList();
      }
    },
    onCopy(id) {
      if (!id) {
        return;
      }
      this.reset();
      this.title = "复制数据报告";
      this.open = true;
      this.form.reportId = id;
      this.isCopy = true;
      this.getInfo();
    },
    getInfo() {
      getBsDataReport(this.form.reportId).then((response) => {
        this.loading = false;
        this.form = response.data;
        if (this.isCopy) {
          // 定义支付串
          const paymentString = response.data.ypCode;
          // 截取支付串的后三位
          const lastThreeDigits = paymentString.slice(-3);
          // 将后三位转换为数字并加1
          const incrementedNumber = parseInt(lastThreeDigits, 10) + 1;
          // 将加1后的数字转换回三位字符串，如果不足三位则前面补零
          const incrementedString = incrementedNumber.toString().padStart(3, "0");
          // 截取支付串的前部分（去掉最后三位）
          const paymentStringPrefix = paymentString.slice(0, -3);
          // 拼接新的支付串
          this.form.ypCode = paymentStringPrefix + incrementedString;
        }
        this.excelTypeIdList = this.form.excelTypeIdList;
        this.setSelection();
        this.setBsJctzStr();
      });
    },
    /** 查询Excel类型管理列表 */
    getExcelTypeList() {
      if (!this.form.syType) {
        return;
      }
      let param = {
        syTypeId: this.form.syType
      };
      this.typeLoading = true;
      listBiExcelType(param).then((response) => {
        this.biExcelTypeList = response.rows;
        this.typeLoading = false;
        if (this.excelTypeIdList.length > 0) {
          this.setSelection();
        }
      });
    },
    // 获取编号规则
    getRuleResList() {
      let param = {
        deptId: this.deptId,
        syTypeId: this.form.syType
      };
      getRuleRes(param).then((response) => {
        this.form.ypCode = response.data.ypCode;
        this.form.bgCode = response.data.bgCode;
        this.form.jlCode = response.data.jlCode;
      });
    },
    // 获取预选分组
    getBsReportGroup() {
      this.groupLoading = true;
      this.reportGroupParams.syTypeId = this.form.syType;
      listBsReportGroup(this.reportGroupParams).then((response) => {
        this.bsReportGroupList = response.rows;
        this.total = response.total;
        this.groupLoading = false;
      });
    },
    // 选中分组
    handleCurrentChange(val) {
      this.currentGroup = val;
      this.excelTypeIdList = val.excelTypeIdList;
      this.setSelection();
    },
    // 设置选中
    setSelection() {
      this.$nextTick(() => {
        this.$refs.typeTable.clearSelection();
        const arr = [...this.excelTypeIdList];
        this.biExcelTypeList.forEach((item) => {
          // 是否包含
          if (arr.includes(item.excelTypeId)) {
            this.$refs.typeTable.toggleRowSelection(item, true);
          }
        });
      });
    },
    // 多选框选中类型
    selectionChange(selection) {
      this.form.excelTypeIdList = selection.map((item) => item.excelTypeId);
    },
    // 保存分组
    onAddGroup() {
      if (this.form.excelTypeIdList.length <= 0) {
        this.$message.warning("请选择实验类型");
        return;
      }
      this.$refs.bsReportGroupViewRef.initView(this.form.excelTypeIdList);
    },

    // 显示进场台账
    showBsJctzView() {
      this.$refs.bsJctzViewRef.init(this.form.checkDeptId || this.deptId);
    },
    bsJctzCallBack(row) {
      this.form.tzId = row.tzId;
      this.form.tzVo = { ...row };
      this.setBsJctzStr();
    },
    // 组装显示
    setBsJctzStr() {
      if (!this.form.tzVo) {
        return;
      }
      const newArr = this.tzTypeList.map((item) => {
        return this.form.tzVo[item] || "";
      });
      this.$set(this.form, "tzStr", newArr.join(","));
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.$refs.groupTable.setCurrentRow();
      this.$refs.typeTable.clearSelection();
      this.buttonLoading = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        reportId: undefined,
        syType: this.syType,
        deptId: this.deptId,
        reportName: undefined,
        reportDate: undefined,
        bgCode: undefined,
        ypCode: undefined,
        jlCode: undefined,
        contractId: undefined,
        ypVo: {},
        excelTypeIdList: [],
        tzId: undefined,
        tzStr: undefined,
        tzVo: {},
        reportDateEnd: undefined,
        dataJsonLabel: undefined,
        dataJson: undefined
      };
      this.resetForm("form");
      this.reportGroupParams = {
        syTypeId: this.syType,
        deptId: this.deptId,
        groupName: undefined
      };
      this.currentGroup = undefined;
      this.excelTypeIdList = [];
      this.isCopy = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          // 处理物联数据
          this.setWlsj();
          // 处理报告编号
          this.disposeCode();
          if (this.form.reportId != null) {
            let request = updateBsDataReport;
            if (this.isCopy) {
              request = copyBsDataReport;
            }
            request(this.form)
              .then((response) => {
                this.$modal.msgSuccess(`${this.isCopy ? "复制" : "修改"}成功`);
                this.cancel();
                this.$emit("callBack");
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addBsDataReport(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.cancel();
                this.$emit("callBack");
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    // 处理报告编号
    disposeCode() {
      let reportName = null;
      // 分割字符串
      const arr = this.form.ypCode.split("-");
      if (arr.length > 1) {
        // 删除第一个
        arr.shift();
        reportName = arr.join("-");
      }
      this.form.bgCode = "BG-" + reportName;
      this.form.jlCode = "JL-" + reportName;
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.labFlag && node.labFlag == 1) {
        node.isDisabled = false;
      } else {
        node.isDisabled = true;
      }
      return {
        ...node,
        id: node.id,
        label: node.label,
        children: node.children
      };
    },
    /** 逐级获取父节点名称 by winterwa -- start ---*/
    findParentPath(nodeId, options, path = []) {
      for (const option of options) {
        if (option.id === nodeId) {
          return [...path, option.label];
        }
        if (option.children) {
          const childPath = this.findParentPath(nodeId, option.children, [...path, option.label]);
          if (childPath) {
            return childPath;
          }
        }
      }
      return null;
    },
    onNodeSelect(nodeId) {
      if (!nodeId) {
        return;
      }
      const path = this.findParentPath(nodeId, this.treeData);
      if (path) {
        const joinedPath = path.join("/");
        // console.log(joinedPath) // 用“/”拼接并输出父节点名称
        this.deptName = joinedPath;
      }
    },

    /** 逐级获取父节点名称 by winterwa -- end ---*/
    handleWlsj() {
      this.$refs.introduceIoTdataView.init();
    },
    tableSelection(val) {
      this.multipleSelection = val;
      if (this.multipleSelection?.length) {
        this.form.dataJsonLabel = "以引入" + this.multipleSelection?.length + "条物联数据";
      } else {
        this.form.dataJsonLabel = "未引入物联数据";
      }
    },
    setWlsj() {
      if (this.multipleSelection?.length) {
        const name = this.multipleSelection[0].keyName;
        let data = {
          [name]: this.multipleSelection
        };
        this.form.dataJson = JSON.stringify(data);
      } else {
        this.form.dataJson = "{}";
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.tips {
  ::v-deep {
    .el-divider__text.is-center {
      width: 60%;
    }
  }
}

::v-deep .radio-border .cell {
  display: flex;
  justify-content: center;
  padding-right: 0;
}

// ::v-deep .no-select {
//   cursor: not-allowed;
// }

::v-deep .no-select {
  cursor: not-allowed;

  .cell {
    pointer-events: none;

    /* 防止鼠标点击事件 */
    .el-checkbox__inner {
      background-color: #f2f6fc;
      border-color: #dcdfe6;

      &::after {
        border-color: #c0c4cc;
      }
    }
  }
}
</style>
